﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace PHRClient.Util
{
    class XMLDatabase
    {
        private const string XMLFILE = "data.xml";

        public void WriteXML(Data data) 
        {
            XmlSerializer writer = new XmlSerializer(typeof(Data));
            FileStream fs = File.Open(XMLFILE, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            writer.Serialize(fs, data);  
        
        }

        public void XmlWriter(Data data)
        {

            try
            {
                XmlSerializer writer = new XmlSerializer(typeof(Data));

                if (!File.Exists(XMLFILE))
                {
                    using (FileStream file = File.OpenWrite(XMLFILE))
                    {
                        writer.Serialize(file, data);
                    }
                    //FileStream fs = File.Open(XMLFILE, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                    //writer.Serialize(fs, data);                   

                }
                else
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(XMLFILE);



                        XmlWriterSettings writtersetting = new XmlWriterSettings();
                        writtersetting.OmitXmlDeclaration = true;

                        StringWriter stringwriter = new StringWriter();
                        using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(stringwriter, writtersetting))
                        {
                            writer.Serialize(xmlwriter, data);
                        }



                        doc.Save(XMLFILE);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        public List<Data> ReadXMLList(string userId)
        {
            Data temp;
            List<Data> dataList = null ;

            XmlSerializer reader = new XmlSerializer(typeof(Data));            

            using (FileStream input = File.OpenRead(XMLFILE))
            {
                temp = reader.Deserialize(input) as Data;
                if (userId.Equals(temp.UserId))
                {
                    dataList.Add(temp);
                }
            }

            return dataList;
        }
    }
}

